<template>
	<el-dialog
			title="编辑XSLT模板"
			v-model="visible"
			width="1000px"
			@close="handleClose">
		<Codemirror
				className="code-mirror"
				:value="content"
				:options="cmOptions"
				border
				ref="cmRef"
				height="500px"
				style="width: 100%"
				@change="onChange"
				@input="onInput"
				@ready="onReady"
		/>
		<template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
			<el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import "codemirror/mode/xml/xml.js"
import Codemirror from "codemirror-editor-vue3"
import "codemirror/theme/ayu-mirage.css";
import "codemirror/theme/neo.css";
import {EditorConfiguration} from "codemirror";

const props = defineProps({
	"content": {
		type: String,
		default: ''
	}
})

const emit = defineEmits(['on-edit'])

const contentTmp = ref('')

const cmRef = ref()
const cmOptions: EditorConfiguration = {
	mode: "xml",
	lineNumbers: true, // Show line number
	smartIndent: true, // Smart indent
	indentUnit: 4, // The smart indent unit is 2 spaces in length
	foldGutter: true, // Code folding
	// matchBrackets: true,
	// autoCloseBrackets: true,
	// styleActiveLine: true, // Display the style of the selected row
	readOnly: false,
	theme: 'ayu-mirage',
}

const visible = ref(false);

/**
 * 关闭弹窗
 */
function handleClose() {
	visible.value = false;
}

function handleSave() {
	emit('on-edit', contentTmp.value);
	handleClose();
}

const onChange = (val: any, cm: any) => {
	// console.log(cm.getValue())
}

const onInput = (val: any) => {
	contentTmp.value = val
}

const onReady = (cm: any) => {
	// console.log(cm.focus())
}

onMounted(() => {
	setTimeout(() => {
		cmRef.value?.refresh()
	}, 1000)

	setTimeout(() => {
		// cmRef.value?.resize(300, 200)
	}, 2000)

	setTimeout(() => {
		cmRef.value?.cminstance.isClean()
	}, 3000)
})

onUnmounted(() => {
	cmRef.value?.destroy()
})

// 打开
const showEditor = (data?: any) => {
	visible.value = true;
}

defineExpose({
	showEditor
})

</script>

<style lang="scss" scoped>
.code-mirror {
	width: max-content;
	font-size: 13px;
	line-height: 120%;
}
</style>
